import 'package:flutter/material.dart';
import 'package:play_android/com/zhihaoliang/base/BaseState.dart';
import 'package:play_android/com/zhihaoliang/const/AppApi.dart';
import 'package:play_android/com/zhihaoliang/http/HttpException.dart';
import 'package:play_android/com/zhihaoliang/play/common/article/ArticleItem.dart';
import 'package:play_android/com/zhihaoliang/play/home/view/ArticleItemPage.dart';
import 'package:play_android/com/zhihaoliang/play/presenter/ArticlePresenter.dart';
import 'package:play_android/com/zhihaoliang/widget/EndLine.dart';
import 'package:play_android/com/zhihaoliang/widget/NoData.dart';

class SearchListPage extends StatefulWidget {

  final String searchkey;

  SearchListPage(this.searchkey);

  @override
  State<StatefulWidget> createState() {
    return _SearchListPageState();
  }}

class _SearchListPageState extends State<SearchListPage> with BaseState implements ArticleCallBack{

  ///文章的列表数据
  List<ArticleItem> _listData;

  ///获取首页列表数据
  ArticlePresenter _articlePresenter;

  //滑动控件
  ScrollController _contraller = ScrollController();

  _SearchListPageState() {
    _contraller.addListener(() {
      if (_articlePresenter == null) {
        return;
      }

      if (_articlePresenter.isEnd()) {
        return;
      }

      var maxScroll = _contraller.position.maxScrollExtent;
      var pixels = _contraller.position.pixels;

      if (maxScroll == pixels) {
        _articlePresenter.load();
      }
    });
  }

  @override
  void initState() {
    super.initState();

    _articlePresenter = new ArticlePresenter(this,AppApi.ARTICLE_QUERY,{"k":widget.searchkey});
    _articlePresenter.loadFrist();
  }

  @override
  void dispose() {
    _contraller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (_listData == null) {
      return Center(
        child: new CircularProgressIndicator(),
      );
    }

    if (_listData.length == 0) {
      return Center(
        child: new NoData(),
      );
    }

    return ListView.builder(
      itemCount: _listData.length ,
      itemBuilder: (context, postion) => _buildItem(postion),
      controller: _contraller,
    );
  }

  Widget _buildItem(int postion) {

    ArticleItem homeItem = _listData[postion];
    if (homeItem.type == ArticleItem.END) {
      return EndLine();
    }

    return ArticleItemPage.isFromSearch(homeItem,widget.searchkey);
  }

  @override
  void onLoadArticleComplete(List<ArticleItem> homeData) {
    setState(() {
      _listData = homeData;
    });
  }

  @override
  void onLoadArticleError(HttpException httpException) {
    if (!_articlePresenter.isFrist()) {
      return;
    }
    onTipError(httpException, context, "获取主页数据失败");
  }
}
